using System;
using System.Web;
using OccurrencesCore.Service;
using OccurrencesCore.Model;

namespace OccurrencesCore.Utility
{
    public class ConfigurationHelper
    {
        private const int CACHE_EXPIRATION_TIME = 5;

        /// <summary>
        /// get the cached parameters value or get from the data
        /// </summary>
        /// <param name="parameterKey">Parameter Key</param>
        /// <returns>Sting with the value.</returns>
        public string GetParameterValue(string parameterKey)
        {
            if (HttpContext.Current.Cache[parameterKey] != null)
                return HttpContext.Current.Cache[parameterKey].ToString();

            ApplicationConfiguration listParameter = new ApplicationConfigurationService().FindByKey(parameterKey);
            if (listParameter == null)
                return string.Empty;

            string result = listParameter.Value;
            HttpContext.Current.Cache.Insert(parameterKey,
                                            result,
                                            null,
                                            System.Web.Caching.Cache.NoAbsoluteExpiration,
                                            new TimeSpan(0, CACHE_EXPIRATION_TIME, 0));

            return result;
        }

        /// <summary>
        /// Remove the configuration parameter from cache
        /// </summary>
        /// <param name="parameterKey">Parameter key</param>
        public void ClearParameterCache(string parameterKey)
        {
            //add from cache
            HttpContext.Current.Cache.Remove(parameterKey);
        }

        public int NumberGridItemsPerPage
        {
            get
            {
                return int.Parse(
                    GetParameterValue(CoreConstants.NUMBER_GRID_ITEMS_PER_PAGE)
                    );
            }
        }

        public string IsDebugEnabled
        {
            get { return GetParameterValue(CoreConstants.APP_CONFIG_FLAG_ISDEBUGENABLED); }
        }

    }
}
